package com.idb.utils;

import cn.hutool.core.lang.Singleton;
import cn.hutool.db.DbUtil;
import cn.hutool.db.handler.RsHandler;
import cn.hutool.db.sql.SqlExecutor;
import cn.hutool.log.Log;
import com.idb.dataSource.IdbDataSource;
import com.idb.yml.OpsYml;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

public class IdbSql {
    private static final Log log = Log.get();
    private IdbSql(){

    }

    public static IdbSql getInstance() {
        return Singleton.get(IdbSql.class);
    }




    public IdbDataSource getDataSource(OpsYml.ExecuteYml executeYml) {
        IdbDataSource dataSource = new IdbDataSource();
        dataSource.init(executeYml.getJdbc(),executeYml.getUsername(), executeYml.getPassword(),executeYml.getDriver());
        return dataSource;
    }

    public Connection getConnect(OpsYml.ExecuteYml executeYml) throws SQLException {
        return getInstance().getDataSource(executeYml).getConnection();
    }

    public int execute(Connection connection,String sql,Map<String,Object> paramsMap) {
        try {
            return SqlExecutor.execute(connection,sql,paramsMap);
        } catch (Exception e) {
            log.error(">>> 执行数据库操作出错：",e);
            throw new RuntimeException(e);
        }
    }

    public <T> T query(Connection connection,String sql, Map<String,Object> paramsMap, RsHandler<T> rsHandler) {
        try {
            return SqlExecutor.query(connection,sql,rsHandler,paramsMap);
        } catch (Exception e) {
            log.error(">>> 执行数据库操作出错：",e);
            throw new RuntimeException(e);
        } finally {
            DbUtil.close(connection);
        }
    }
}
